import os

from django.contrib.auth import get_user_model
from shortuuid import uuid
from django.conf import settings
from django.utils.translation import gettext_lazy as _
from rest_framework.generics import ListAPIView, RetrieveAPIView, CreateAPIView, DestroyAPIView, UpdateAPIView
from rest_framework.exceptions import AuthenticationFailed

from utils import exception
from utils.response import APIResponse, Code

"""
重写返回数据格式APIResponse

        # 添加作者
        data = request.data.copy()  # QuerDyict不可变， copy后操作
        data['author_id'] = request.auth.user.id

"""


class BaseCustom(object):
    def throttled(self, request, wait):
        """
        If request is throttled, determine what kind of exception to raise.
        """
        raise exception.ThrottledException('访问频率过快~~')


class CustomList(BaseCustom, ListAPIView):
    """
    多条数据
    """

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return APIResponse(msg="获取成功~~", data=serializer.data)


class CustomRetrieve(BaseCustom, RetrieveAPIView):
    """
    单条详情
    """

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return APIResponse(msg="获取成功~~", data=serializer.data)


class CustomCreate(BaseCustom, CreateAPIView):
    """
    创建
    """

    def create(self, request, *args, **kwargs):
        # 添加作者
        data = request.data.copy()  # QuerDyict不可变， copy后操作
        data['author_id'] = request.user.id
        serializer = self.get_serializer(data=data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return APIResponse(msg='发布成功~~', data=serializer.data, status=201, headers=headers)


class CustomUpdate(BaseCustom, UpdateAPIView):
    """
    更新
    """

    def update(self, request, *args, **kwargs):
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)

        if getattr(instance, '_prefetched_objects_cache', None):
            instance._prefetched_objects_cache = {}

        return APIResponse(msg='更新成功~~', data=serializer.data)


class CustomDestroy(BaseCustom, DestroyAPIView):
    """
    删除
    """

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        self.perform_destroy(instance)
        return APIResponse(msg='删除成功')


class UploadAPIView(BaseCustom, CreateAPIView):

    def create(self, request, *args, **kwargs):
        file = request.data.get('file')
        if file:
            ext = file.name.split('.')[-1]
            uuid_name = f"{uuid()}.{ext}"
            with open(os.path.join(settings.MEDIA_ROOT, uuid_name), 'wb') as ff:
                for chunk in file.chunks():
                    ff.write(chunk)
            url = request.build_absolute_uri(settings.MEDIA_URL + uuid_name)
            return APIResponse(msg='上传成功~~', data={
                "src": url,
                "title": uuid_name
            })
        return APIResponse(code=Code.BadParams, msg='上传失败~~')
